package com.iflytek.jzcpx.procuracy.common.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.jzcpx.procuracy.common.enums.MetricEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MetricUtil {
	private static final Logger logger = LoggerFactory.getLogger(MetricUtil.class);

	/**
	 * 从HttpServletRequest 获取ip地址 (周伟新增)
	 * 
	 * @param request
	 * @return 远端ip地址
	 */
	public static String getRemoteIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}

	public static JSONObject buildMetricParam(HttpServletRequest request, MetricEnum metricEnum, String interfaceName) throws Exception {
		Long startMillis = System.currentTimeMillis();
		JSONObject obj = new JSONObject();
		obj.put("startMillis", startMillis);
		obj.put("callerIp", getRemoteIpAddr(request));
		// obj.put("serviceIp", InetAddress.getLocalHost().getHostAddress());
		obj.put("serviceIp", getServiceIp());
		obj.put("systemid", request.getHeader("systemid"));
		obj.put("mrtricType", metricEnum.name());
		obj.put("interfaceName", interfaceName);
		obj.put("createTime", new Date());
		obj.put("ocrStartTime", new Date());
		obj.put("dwbm", request.getParameter("dwbm"));
		obj.put("ajlbbm", request.getParameter("ajlbbm"));
		obj.put("bmsah", request.getParameter("bmsah"));
		return obj;
	}

	private static String getServiceIp() {
		String hostIP = StringUtils.EMPTY;
		ArrayList<String> ipList = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
				Enumeration<InetAddress> ipAddrEnum = ni.getInetAddresses();
				while (ipAddrEnum.hasMoreElements()) {
					InetAddress addr = (InetAddress) ipAddrEnum.nextElement();
					if (addr.isLoopbackAddress() == true) {
						continue;
					}
					String ip = addr.getHostAddress();
					if (ip.indexOf(":") != -1) {
						// skip the IPv6 addr
						continue;
					}
					ipList.add(ip);
				}
			}
			Collections.sort(ipList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (CollectionUtils.isNotEmpty(ipList)) {
			hostIP = ipList.get(ipList.size() - 1);
		}
		return hostIP;
	}
}
